<template>
  <div class="edu-page-warp">
    <el-row :gutter="0">
      <el-col :span="12">
        <p class="section-title">任务编辑</p>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-button @click="goback" icon="el-icon-back">返回列表</el-button>
      </el-col>
    </el-row>
    <el-card shadow="never" body-style="padding: 24px;">
      <el-form ref="newerTask" :model="newerTask" :rules="taskRules" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="年级" prop="year">
              <el-select v-model="newerTask.year" placeholder="请选择年级" style="width: 100%" @change="getPreTasks">
                <el-option v-for="item in options.grade" :key="item.value"
                           :label="item.label + '级'"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培养层次" prop="trainingLevel">
              <el-select multiple v-model="newerTask.trainingLevel" placeholder="请选择培养层次" style="width: 100%">
                <el-option v-for="(item, index) in options.trainingLevel" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国际学生">
              <el-select v-model="newerTask.isStudentAbroad" placeholder="请选择" style="width: 100%">
                <el-option label="全部" value="2"></el-option>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="必做">
              <el-switch
                v-model="newerTask.isRequired"
                active-value= "0"
                inactive-value= "1">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="任务排序" prop="oreder">
              <el-input-number v-model="newerTask.oreder" placeholder="请输入任务排序" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务名称" prop="templateName">
              <el-input v-model="newerTask.templateName" placeholder="请输入任务名称" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文标语" prop="sloganInChinese">
              <el-input v-model="newerTask.sloganInChinese" placeholder="请输入中文标语" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文标语" prop="sloganInEnglish">
              <el-input v-model="newerTask.sloganInEnglish" placeholder="请输入英文标语" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
             <!-- placeholder="选择开始时间" -->
            <el-form-item label="开始时间" prop="beginTime" style="width: 100%">
              <el-date-picker
                v-model="newerTask.beginTime"
                type="datetime"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- placeholder="选择结束时间" -->
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="newerTask.endTime"
                type="datetime"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用外链" style="width: 100%">
              <el-switch
                v-model="newerTask.hasExtenalLink"
                active-value='1'
                inactive-value='0'
                @change="hasExtenalLink">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="options.showLink">
            <el-form-item label="外链地址" prop="extenalLink">
              <el-input v-model="newerTask.extenalLink" placeholder="请输入外链地址" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="前置任务">
              <el-select multiple v-model="newerTask.templateIdList" placeholder="请选择前置任务" style="width: 100%">
                <el-option v-for="(item, index) in options.relyPredecessorsList" :key="index" :label="item.templateName"
                           :value="item.templateId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="允许手机">
              <el-switch
                v-model="newerTask.isPhone"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="任务简介" prop="introduction">
              <el-input type="textarea" :rows="4" v-model="newerTask.introduction" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务配图">
              <el-upload
                class="avatar-uploader"
                action="/api/commonservice/obsfile/uploadimage"
                :data="{bucketname: 'face', folderpath: 'image'}"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item class="editor" label="任务详情" prop="details">
              <editor class="editor" :value="newerTask.details" v-model="newerTask.details" :setting="editorSetting" @input="(details)=> details = details"></editor>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="text-right">
          <el-button @click="resetForm('newerTask')">取消</el-button>
          <el-button type="primary" @click="submitForm('newerTask')">提交任务</el-button>
        </div>
      </el-form>
    </el-card>
  </div>

</template>
<script>
import {
  createNewTask,
  getTasks,
  getTasksNoDetail,
  updateTask,
  getDicByType
} from "common/src/api/welcomeService/taskTemplate";
import { downloadimage, downloadfile } from "common/src/api/upload";
import { queryDic } from "common/src/api/dictionary";
import Bus from "common/src/utils/bus";
import editor from "common/src/components/tinymce/editor";

export default {
  name: "EditNewerTask",
  components: {
    editor
  },
  data() {
    var validateEndTime = (rule, value, callback) => {
      let startTime = this.newerTask.beginTime;
      let endTime = value;
      if (startTime > endTime) {
        callback(new Error("结束时间不能小于开始时间"));
      } else {
        callback();
      }
    };
    const getGrade = (function() {
      let now = new Date().getFullYear();
      let years = [];
      for (let i = 0; i < 3; i++) {
        years.push({
          label: now + i,
          value: now + i
        });
      }
      return years;
    })();
    return {
      currentPath: "",
      imageUrl: "",
      options: {
        trainingLevel: [],
        grade: getGrade,
        studentType: [],
        relyPredecessorsList: [],
        showLink: false
      },
      editorSetting: {
        height: 500
      },
      newerTask: {
        year: '',
        trainingLevel: [],
        isStudentAbroad: '',
        oreder: '',
        templateName: '',
        sloganInChinese: '',
        sloganInEnglish: '',
        beginTime: '',
        endTime: '',
        hasExtenalLink: '',
        extenalLink: '',
        templateIdList: [],
        introduction: '',
        details: '',
        picturePath: '',
        isPhone: '',
        isRequired: '',
        templateType: ''
      },
      taskRules: {
        year: [{ required: true, message: "请选择年级", trigger: "change" }],
        templateName: [
          { required: true, message: "请输入名称", trigger: "blur" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        oreder: [
          { required: true, message: "请输入任务顺序", trigger: "blur" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        trainingLevel: [
          { required: true, message: "请选择培养层次", trigger: "change" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        sloganInChinese: [
          { required: true, message: "请输入中文标语", trigger: "blur" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        sloganInEnglish: [
          { required: true, message: "请输入英文标语", trigger: "blur" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        beginTime: [
          { required: true, message: "请选择开始日期", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择结束日期", trigger: "change" },
          { validator: validateEndTime, trigger: "blur" }
        ]
        // details: [
        //   {required: true, message: "请输入任务详情", trigger: "blur"}
        // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        // ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.$route.params.taskId) {
            updateTask(this.newerTask).then(res => {
              this.$refs[formName].resetFields();
              this.newerTask.trainingLevel = [];
              this.newerTask.templateIdList = [];
              this.$message({
                message: "任务更新成功",
                type: "success"
              });
              this.$store.commit("delete_tabs", this.currentPath);
              Bus.$emit("editSuccess", res);
              this.$router.push("/newerTasks");
            });
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$store.commit("delete_tabs", this.currentPath);
      this.$refs[formName].resetFields();
      this.$router.push("/newerTasks");
      this.$store.commit("delete_tabs", this.currentPath);
    },
    goback() {
      this.$store.commit("delete_tabs", this.currentPath);
      this.$router.push("/newerTasks");
    },
    hasExtenalLink(val) {
      this.options.showLink = val == 0 ? false : true;
      if (val == 0) {
        this.newerTask.extenalLink = "";
      }
    },
    handleAvatarSuccess(res, file) {
      this.newerTask.picturePath = res.data.file.objectkey;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarError(res, file) {
      this.$message({
        message: "任务配图上传上传失败",
        type: "error"
      });
    },
    beforeAvatarUpload(file) {
      const isAccept = ["image/jpeg", "image/png"].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isAccept) {
        this.$message.error("上传图片只能是 JPG 或者 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isAccept && isLt2M;
    },
    getPreTasks(val) {
      this.options.relyPredecessorsList = [];
        let query = {
          year: val,
          pageNum_: 1,
          pageSize_: 10000
        };
        getTasksNoDetail(query).then(allTasks=>{
          if (allTasks.data && allTasks.data.list.length > 0) {
            this.options.relyPredecessorsList = allTasks.data.list;
          }
        }).catch(res=>{});
    },
    initOptions() {
      // let data = {
      //   lang: this.$store.getters.language || "cn",
      //   type: "allChild",
      //   keys: ["X_PYCC"]
      // };
      // queryDic(data)
      //   .then(res => {
      //     if (res.code == 200) {
      //       this.fillSelect(res.data);
      //     }
      //   })
      //   .catch(res => {});
      getDicByType("X_PYCC").then(res =>{
        if(res.code == 200){
          this.fillSelect(res.data);
        }
      })
    },
    fillSelect(data) {
      this._fill("trainingLevel", data.X_PYCC);
    },
    _fill(type, data) {
      for (let key in data) {
        if (this.options[type]) {
          this.options[type].push({
            value: key,
            label: data[key]
          });
        }
      }
    }
  },
  created() {
    this.currentPath = this.$router.history.current.path;
    this.getPreTasks();
    this.initOptions();
    let taskId = this.$route.params.taskId;
    if (taskId) {
      getTasks({
        templateId: taskId,
        dic: false,
        pageNum_: 1,
        pageSize_: 20
      })
        .then(res => {
          if (res.code == 200) {
            let taskTrainingLevelList = [];
            let taskList = [];
            res.data.list[0].taskTrainingLevelList.forEach(element => {
              taskTrainingLevelList.push(element.trainingLevel);
            });
            res.data.list[0].relyPredecessorsList.forEach(element => {
              taskList.push(element.depTemplateId);
            });
            res.data.list[0].trainingLevel = taskTrainingLevelList;
            res.data.list[0].templateIdList = taskList;
            res.data.list[0].isStudentAbroad =
              "" + res.data.list[0].isStudentAbroad;
            res.data.list[0].hasExtenalLink =
              "" + res.data.list[0].hasExtenalLink;
            res.data.list[0].isRequired =
              "" + res.data.list[0].isRequired;
            res.data.list[0].isPhone =
              "" + res.data.list[0].isPhone;
            this.options.showLink =
              res.data.list[0].hasExtenalLink == 1 ? true : false;
            if (res.data.list[0].picturePath) {
              downloadimage(res.data.list[0].picturePath).then(res => {
                if (res && res.data) {
                  this.imageUrl = res.data.base;
                }
              });
            }
            this.newerTask = res.data.list[0];
          } else {
            throw res;
          }
        })
        .catch(res => {
          this.$message.error("查询任务信息失败，无法更新任务！");
        });
    }
  }
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: dashed 1px #d2d4d6;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>
